package com.igame.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.igame.dto.HistoryDto;
import com.igame.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@Slf4j
public class RedisConfiguration {
    @Bean
    public RedisTemplate<String, User> redisTemplate(RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) {
        RedisTemplate<String, User> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 设置键（key）的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());

        // 使用自定义的 Jackson2JsonRedisSerializer 作为值（value）的序列化方式
        CustomJackson2JsonRedisSerializer<User> serializer = new CustomJackson2JsonRedisSerializer<>(User.class, objectMapper);
        redisTemplate.setValueSerializer(serializer);

        // 设置 hash 的 key 和 value 的序列化方式
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);

        return redisTemplate;
    }

    @Bean
    public RedisTemplate<String, HistoryDto> historyDtoRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, HistoryDto> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置键的序列化方式
        template.setKeySerializer(new StringRedisSerializer());

        // 使用 GenericJackson2JsonRedisSerializer 作为值的序列化方式
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;
    }
}
